package com.atguigu.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.vod.Utils.ConstantVodUtils;
import com.atguigu.vod.Utils.InitVodClient;
import com.atguigu.vod.service.VodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
public class VodController {
    @Autowired
    private VodService vodService;
    //上传视频的方法
    @PostMapping("upload")
    public R uploadAliyunVideo(MultipartFile file) {
        //返回上传视频的ID值
        String videoId = vodService.uploadVideoAly(file);
        return R.ok().data("videoId", videoId);
    }
    //根据视频ID删除视频
    @DeleteMapping("remove/{id}")
    public R removeAliyunVideo(@PathVariable String id) {
        try {
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建一个删除视频的request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //向request设置视频id
            request.setVideoIds(id);

            client.getAcsResponse(request);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "删除视频失败");
        }
    }
    //删除多个阿里云视频的方法
    //参数是多个视频ID
    @DeleteMapping("deleteBatch")
    public R deleteBatch(@RequestParam("videoIdList") List<String> voidIdList) {
        vodService.removeMoreAlyVideo(voidIdList);
        return R.ok();
    }

    //根据视频id获取凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) {
        //根据视频ID获取视频播放凭证
        //创建初始化对象
        try {
            DefaultAcsClient client =  InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //获取视频凭证的request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
            //向request设置视频id
            request.setVideoId(id);
            //调用初始化对象的方法得到凭证
            response = client.getAcsResponse(request);
            return R.ok().data("playAuth", response.getPlayAuth());
        } catch (ClientException e) {
            throw new GuliException(20001, "获取凭证失败");
        }
    }
}
